//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.xjrsoft.module.bi.common.tool;

import cn.hutool.extra.spring.SpringUtil;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.lang.Nullable;

import java.util.concurrent.Callable;

public class CacheUtil {
    public static final String SYS_CACHE = "blade:sys";
    private static CacheManager cacheManager;

    public CacheUtil() {
    }

    private static CacheManager getCacheManager() {
        if (cacheManager == null) {
            cacheManager = (CacheManager) SpringUtil.getBean(CacheManager.class);
        }

        return cacheManager;
    }

    public static Cache getCache(String cacheName) {
        return getCacheManager().getCache(cacheName);
    }

    @Nullable
    public static Object get(String cacheName, String keyPrefix, Object key) {
        return Func.hasEmpty(new Object[]{cacheName, keyPrefix, key}) ? null : getCache(cacheName).get(keyPrefix.concat(String.valueOf(key))).get();
    }

    @Nullable
    public static <T> T get(String cacheName, String keyPrefix, Object key, @Nullable Class<T> type) {
        return Func.hasEmpty(new Object[]{cacheName, keyPrefix, key}) ? null : getCache(cacheName).get(keyPrefix.concat(String.valueOf(key)), type);
    }

    @Nullable
    public static <T> T get(String cacheName, String keyPrefix, Object key, Callable<T> valueLoader) {
        if (Func.hasEmpty(new Object[]{cacheName, keyPrefix, key})) {
            return null;
        } else {
            try {
                Cache.ValueWrapper valueWrapper = getCache(cacheName).get(keyPrefix.concat(String.valueOf(key)));
                Object value = null;
                if (valueWrapper == null) {
                    T call = valueLoader.call();
                    if (Func.isNotEmpty(call)) {
                        getCache(cacheName).put(keyPrefix.concat(String.valueOf(key)), call);
                        value = call;
                    }
                } else {
                    value = valueWrapper.get();
                }

                return (T) value;
            } catch (Exception var7) {
                var7.printStackTrace();
                return null;
            }
        }
    }

    public static void put(String cacheName, String keyPrefix, Object key, @Nullable Object value) {
        getCache(cacheName).put(keyPrefix.concat(String.valueOf(key)), value);
    }

    public static void evict(String cacheName, String keyPrefix, Object key) {
        if (!Func.hasEmpty(new Object[]{cacheName, keyPrefix, key})) {
            getCache(cacheName).evict(keyPrefix.concat(String.valueOf(key)));
        }
    }

    public static void clear(String cacheName) {
        if (!Func.isEmpty(cacheName)) {
            getCache(cacheName).clear();
        }
    }
}
